%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Explanation of what the file does
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% This function computes a new guess for wages and labor (hats or dots) 
% given an initial guess in the RUV economy with forward looking migration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Inputs needed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% 1. Previous trade shares (PastSha), size I*I*S
% 2. Dot or hat trade costs (TAUmatrix), size I*I*S
% 3. Dot or hat technologies (TECmatrix), size I*S
% 4. Labor shares (labshares), size I*S
% 5. IO matrix (inoutmat), size I*S*S
% 6. Trade elasticities (Smatrix), size 1*S
% 7. Final good consumption shares (Amatrix), size I*S
% 8. Previous income by sector (PastYnom), size I*S
% 9. Limit to labor dots (Llim), size I*S
% 10. Limit to wage dots (Wlim), size I*S
% 11. Deficit levels (Deficits), size I
% 12. An initial guess for wages dot or hat (Wguess), size I*S
% 13. An initial guess for labors dot or hat (Lguess), size I*S
% 14. Lambda for the tatonnement algorithm (lambda), scalar
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Outputs produced
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% 1. New guess for wages dot or hat (Wnew), size I*S
% 2. New guess for labors dot or hat (Lnew), size I*S
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Matlab functions invoked
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% 1. NEBA_PriceSolver
% 2. NEBA_RevenueSolver

function [Wnew,Lnew] = NEBA_TatoNewGuess(PastSha,TAUmatrix,TECmatrix,...
labshares,inoutmat,Smatrix,Amatrix,PastYnom,Llim,Wlim,Deficits,...
Wguess,Lguess,lambda)

% Define number of regions and sectors

I             = size(Amatrix,1);
S             = size(Amatrix,2);

% Find new prices dot or hat and trade shares using a function especially 
% designed for this that utilizes a contraction mapping algorithm

[~,shareslev] = NEBA_PriceSolver(ones(I,S),PastSha,TAUmatrix,...
TECmatrix,Wguess,labshares,inoutmat,Smatrix,800,1e-8);
           
% Now obtain new revenues in levels using a function specially designed for
% this that solves a simple (but large) linear system of equations

Vmat          = sum(Wguess .* Lguess .* PastYnom,2) + Deficits;
Revmat        = NEBA_RevenueSolver(shareslev,Vmat,Amatrix,inoutmat);

% Then defined the new guesses for wage and labor dots or hats according to 
% the tatonnement algorithm described in the paper

inter         = (labshares.*Revmat)./PastYnom;
Wnew          = max(((1-lambda)*Wguess.*Lguess+lambda.*inter)./Llim,Wlim);
Lnew          = min(Llim,((1-lambda)*Wguess.*Lguess+lambda.*inter)./Wlim);

end
